package com.ims.listenser;

import com.alibaba.fastjson.JSONObject;
import com.ims.pojo.Status;
import com.ims.service.StatusService;
import com.ims.util.DecryptUtil;
import io.github.majusko.pulsar.annotation.PulsarConsumer;
import io.github.majusko.pulsar.constant.Serialization;
import org.apache.pulsar.client.api.SubscriptionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class StatusInfoListener {

    @Autowired
    private StatusService statusService;

    @PulsarConsumer(topic = "statusinfo",  // 订阅topic名称
            subscriptionName = "ims_server", // 订阅名称
            serialization = Serialization.JSON, // 序列化方式
            subscriptionType = SubscriptionType.Shared, // 订阅模式，默认为独占模式
            consumerName = "ims_server", // 消费者名称
            maxRedeliverCount = 5 // 最大重试次数
//            deadLetterTopic = "sub_topic1-DLQ" // 死信topic名称
    )
    public void topicConsume(byte[] encryptMsg) {
        // TODO process your message
        String decryptMsg = DecryptUtil.sm2Decrypt(new String(encryptMsg));

        JSONObject statusInfo = JSONObject.parseObject(decryptMsg);
        String deviceId = statusInfo.get("device_id").toString();
        String deviceName = statusInfo.get("device_name").toString();
        String eventTime = statusInfo.get("event_time").toString();

        JSONObject cpu = JSONObject.parseObject(statusInfo.get("cpu_status").toString());
        JSONObject ram = JSONObject.parseObject(statusInfo.get("ram_status").toString());
        JSONObject network = JSONObject.parseObject(statusInfo.get("network_adapter_status").toString());

        Status status = new Status();
        status.setDeviceId(deviceId);
        status.setDeviceName(deviceName);
        status.setStatusInfo(statusInfo.toString());

        status.setCpuUsage(cpu.get("usage").toString());
        status.setCpuStatus(Integer.parseInt(cpu.get("status").toString()));

        status.setRamUsage(ram.get("usage").toString());
        status.setRamStatus(Integer.parseInt(ram.get("status").toString()));

        status.setNetworkSendUsage(network.get("send_usage").toString());
        status.setNetworkReceiveUsage(network.get("receive_usage").toString());
        status.setSendUsageStatus(Integer.parseInt(network.get("send_usage_status").toString()));
        status.setReceiveUsageStatus(Integer.parseInt(network.get("receive_usage_status").toString()));

        status.setEventTime(eventTime);

        statusService.save(status);

        System.out.println("Received a new message. content: [" + decryptMsg + "]");
        // 如果消费失败，请抛出异常，这样消息会进入重试队列，之后可以重新消费，直到达到最大重试次数之后，进入死信队列。前提是要创建重试和死信topic
    }
}
